package com.cx.mvc.practise.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cx.mvc.practise.action.MyAction;
import com.cx.mvc.practise.cache.ConfigCache;
import com.cx.mvc.practise.mapping.AcitonMapping;
import com.cx.mvc.practise.parse.vo.XmlBean;
import com.cx.mvc.practise.reflect.MyReflect;
import com.cx.mvc.practise.vo.FormBean;

public class ServletAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取参数
		String urlPath = request.getServletPath().trim();
		//获得xmlbean对象
		XmlBean xmlBean = ConfigCache.getMyStrutsMap().get(getPath(urlPath));
		
		FormBean formBean = MyReflect.reflactFormBean(request, xmlBean.getXmlFormBean().getClassName());
		MyAction myAction = MyReflect.getBusinessAction(xmlBean.getXmlActionBean().getClassName());
		
		//String url = myAction.execute(request, response, formBean, xmlBean.getXmlActionBean().getForword());
		
		String result = myAction.execute(request, response, formBean);
		String url = xmlBean.getXmlActionBean().getForword().get(result);
		
		request.setAttribute("formBean", formBean);
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	private String getPath(String servletPath)
	{
		return servletPath.split("\\.")[0];
	}

	private void practiseOld(HttpServletRequest request,
			HttpServletResponse resp) throws IOException {
		/*resp.setCharacterEncoding("GBK");
		FormBean formbean = MyReflect.assemblingBeanTest(request);
		MyAction myaction = null;
		try {
			myaction = AcitonMapping.getFormBean(request);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String message = myaction.execute(formbean);
		PrintWriter out = resp.getWriter();
		out.append(message);
		out.flush();
		out.close();*/
	}
}
